/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦]
 * 
 * https://zhiqim.org/project/zhiqim_framework/zhiqim_kernel.htm
 *
 * Zhiqim Kernel is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.kernel.transaction;

import java.util.List;

import org.zhiqim.kernel.logging.Log;
import org.zhiqim.kernel.logging.LogFactory;
import org.zhiqim.kernel.util.Arrays;

/**
 * 事务列表管理器，用来对多个实现的事务一起处理
 * 1、管理多个事务
 * 2、本身也设计成一个事务
 *
 * @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
 */
public class TransactionLister extends TransactionAbstracter
{
    private static final Log log = LogFactory.getLog(TransactionLister.class);
    private List<Transaction> txList = null;
    
    public TransactionLister(String[] ids, List<Transaction> txList)
    {
        super(Arrays.toString(ids));
        this.txList = txList;
    }
    
    /** 获取事务列表 */
    public List<Transaction> getTransactionList()
    {
        return txList;
    }
    
    /** 开始所有事务 */
    public Transaction begin() throws Exception
    {
        for (Transaction tx : txList)
            tx.begin();
        
        return this;
    }
    
    /** 提交所有事务 */
    public void commit() throws Exception
    {
        for (Transaction tx : txList)
        {//某个异常即抛出到上一层
            tx.commit();
        }
        
        super.setCommitted();
    }
    
    /** 回滚所有事务 */
    public void rollback() throws Exception
    {
        for (Transaction tx : txList)
        {//不能因为其中一个导致所有的事务都没回滚
            try{tx.rollback();}catch(Exception e){log.error(e);}
        }
        
        super.setRollbacked();
    }
    
    /** 关闭所有事务 */
    public void close() throws Exception
    {
        for (Transaction tx : txList)
        {//不能因为其中一个导致所有的事务都没关闭
            try{tx.close();}catch(Exception e){log.error(e);}
        }
        
        super.setClosed();
    }
}
